/**
 * 
 */
package com.cipe.cmrs.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cipe.cmrs.model.Paymenttype;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.util.DateUtil;
import com.cipe.cmrs.util.UserUtil;
import com.cipe.cmrs.util.Util;

/**
 * @author Incepio
 * 
 */
@Service
@Transactional
public class PaymenttypeService extends BaseService<Paymenttype> {

	public Paymenttype savePaymenttype(Paymenttype paymenttype, Integer userId) {
		if (paymenttype != null) {
			User user = UserUtil.INSTANCE.getCurrentUser();
			Paymenttype dbPaymenttype = findById(paymenttype.getId());
			if (dbPaymenttype == null) {
				dbPaymenttype = new Paymenttype();
				dbPaymenttype.setCreatedBy(user);
				dbPaymenttype.setCreationDate(DateUtil.getCurrentDate());
			}
			dbPaymenttype.setUpdatedBy(user);
			dbPaymenttype.setUpdationDate(DateUtil.getCurrentDate());
			return merge(dbPaymenttype);
		}
		return null;
	}

	/**
	 * @param paymenttypename
	 * @return
	 */
	public Paymenttype findByPaymenttypename(String paymenttypename) {
		Paymenttype paymenttype = null;
		try {
			String query = "from Paymenttype where 1=1 " + Util.createQueryClause("paymenttypename", paymenttypename);
			paymenttype = this.dao.getSingleResult(query);
		} catch (Exception exp) {
			logger.error(exp.getMessage(), exp);
		}
		return paymenttype;
	}

    public List<Paymenttype> getActivePaymentTypes(Integer paymentType) {
        List<Object> parameters = new ArrayList<Object>();
        StringBuilder queryBuilder = new StringBuilder();
        queryBuilder.append("FROM Paymenttype WHERE status = ?");
        parameters.add("A");
        if (paymentType != null && paymentType > 0) {
            queryBuilder.append(" OR id = ? ");
            parameters.add(paymentType);
        }
        queryBuilder.append("ORDER BY paymenttypename ASC");
        return dao.getResultList(queryBuilder.toString(), parameters.toArray(new Object[0]));
    }
}
